package kr.couponplay.android.activity.intro.command;

import kr.couponplay.android.Constants;
import kr.couponplay.android.activity.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Parcelable;

public class ShortcutAddCommand implements Command {
	
	@Override
	public void execute(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
		String oldShoutcutYn = preferences.getString("addedShortcutYn", "N");
		
		if ("Y".equals(oldShoutcutYn)) {
			removeShortcut(context);
		}
		
    	String addedShortcutYn = preferences.getString(Constants.KEY_ADDED_SHORTCUT_YN, "N");
    	if ("Y".equals(addedShortcutYn)) {
    		return;
    	}
	    	
    	Intent shortcutIntent = new Intent();
        shortcutIntent.setAction(Intent.ACTION_MAIN);
        shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shortcutIntent.setClassName(context, getClass().getName());
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
       
        Parcelable iconResource = Intent.ShortcutIconResource.fromContext(context, R.drawable.icon);
       
        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources().getString(R.string.app_name));
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,iconResource);
        intent.putExtra("duplicate", false);
        intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        context.sendBroadcast(intent);
		Editor editor = preferences.edit();
		editor.putString(Constants.KEY_ADDED_SHORTCUT_YN, addedShortcutYn);
		editor.commit();
	}
	
	private void removeShortcut(Context context) {
        Intent shortcutIntent = new Intent();
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "쿠폰플레이");
        intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
        context.getApplicationContext().sendBroadcast(intent);
    }	
}
